﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Mengsk.ProxyDelivery.Service
{
    public class Request
    {
        public string AccessToken { get; set; }

        public string Target { get; set; }

        public string Api { get; set; }

        public List<Parameter> Parameters { get; private set; }

        public Request()
        {
            this.Parameters = new List<Parameter>();
        }

        public string ToXml()
        {
            XDocument doc = XDocument.Parse("<?xml version=\"1.0\" encoding=\"utf-8\" ?><request/>");
            if (string.IsNullOrWhiteSpace(AccessToken) || string.IsNullOrWhiteSpace(Target) || string.IsNullOrWhiteSpace(Api))
            {
                throw new Exception("请求参数不能有空值");
            }

            doc.Root.Add(new XElement("accessToken", AccessToken));
            doc.Root.Add(new XElement("target", Target));
            doc.Root.Add(new XElement("api", Api));

            XElement xele = new XElement("parameters");
            foreach (var p in Parameters)
            {
                XElement xe = p.ToXElement();
                xele.Add(xe);
            }
            doc.Root.Add(xele);

            return doc.ToString();
        }

        public void Add(string key, object value)
        {
            this.Parameters.Add(new Parameter(key, value));
        }
    }
}
